package com.inter.controller.newoutside;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.config.StringOutputConstant;
import com.inter.entity.agatewaytobeijing.JsonConstant;
import com.inter.entity.agatewaytobeijing.querydevice.beijing.response.ResponseQueryDevice;
import com.inter.entity.agatewaytobeijing.querydeviceorder.response.ResponseQueryDeviceOrder;
import com.inter.entity.interentity.querydevicerealtime.request.RequestQueryDeviceRealTime;
import com.inter.entity.interentity.querydevicerealtime.request.RequestQueryDeviceRealTimeData;
import com.inter.entity.interentity.querydevicerealtime.request.RequestQueryDeviceRealTimeTradeData;
import com.inter.entity.interentity.querydevicerealtime.response.ResponseQueryDeviceRealTime;
import com.inter.entity.interentity.querydevicerealtime.response.ResponseQueryDeviceRealTimeData;
import com.inter.entity.interentity.querydevicerealtime.response.ResponseQueryDeviceRealTimeTradeData;
import com.inter.entity.interentity.querydevicerealtime.response.ResponseQueryDeviceRealTimeTradeDataPackageOrder;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.service.agatewaytobeijing.GatewayToBeijingService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 查询设备流量和理论的剩余时间：
 * <p>
 * 专门给大阳使用的
 *
 * @author lm
 * @date 2018/12/25
 */
@RestController
@Api(description = "大阳-单一设备实时信息")
@Slf4j
public class QuerySingleDeviceRealTimeDaYangController {
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    PartnerService partnerService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;
    @Autowired
    GatewayToBeijingService toBeijingService;

    @CrossOrigin
    @RequestMapping(value = "queryDeviceRealTime", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "设备实时信息-专用于大阳", response = ResponseQueryDeviceRealTime.class)
    public String queryDeviceRealTime(@ApiParam @RequestBody RequestQueryDeviceRealTime requestQueryDeviceRealTime) {

        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 2,生成当前时间戳
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestQueryDeviceRealTime);

        if (StringUtils.isBlank(requestStr)) {
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("【设备实时信息-专用于大阳】请求：" + requestStr);
            RequestQueryDeviceRealTime requestPackage = JSONArray.parseObject(requestStr, RequestQueryDeviceRealTime.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                if (null == requestPackage.getData()) {
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    RequestQueryDeviceRealTimeData requestData = requestPackage.getData();
                    if (StringUtils.isBlank(requestData.getPartnerCode()) || StringUtils.isBlank(requestData.getConnSeqNo()) || StringUtils.isBlank(requestData.getTradeTime()) ||
                            StringUtils.isBlank(requestData.getToken()) || StringUtils.isBlank(requestData.getTradeType()) || StringUtils.isBlank(requestData.getLang()) || null == requestData.getTradeData()) {
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        String partnerCode = requestData.getPartnerCode();
                        String partnerName = partnerProductPackageService.queryPartnerNameBypartnerCode(partnerCode);
                        String secret = partnerService.findSecretByPartnerCode(partnerCode);
                        /*logger.info("渠道名称：" + partnerName + ";密钥是：" + secret);*/
                        String ConnSeqNo = requestData.getConnSeqNo();
                        String tradeTime = requestData.getTradeTime();
                        String token = requestData.getToken();
                        String tradeType = requestData.getTradeType();
                        String lang = requestData.getLang();
                        RequestQueryDeviceRealTimeTradeData tradeData = requestData.getTradeData();
                        if (StringUtils.isBlank(requestData.getTradeData().getDeviceId()) || StringUtils.isBlank(requestData.getTradeData().getDeviceType())) {
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            String deviceId = requestData.getTradeData().getDeviceId();
                            String deviceType = requestData.getTradeData().getDeviceType();
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                log.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                /* 2021-05-25：添加修改用3.0企业网关的接口进行查询： 查询设备*/
                                ResponseQueryDevice response = toBeijingService.queryDevice(deviceId, partnerCode, secret);
                                /*没有查到设备信息*/
                                if (null == response || null == response.getCode() || null == response.getData()) {
                                    ResponseQueryDeviceRealTimeData data = new ResponseQueryDeviceRealTimeData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(curtime);
                                    data.setTradeRstCode(1200);
                                    data.setTradeRstMessage("The current device information was not queried;未查询到当前设备信息!");

                                    ResponseQueryDeviceRealTime deviceRealTime = new ResponseQueryDeviceRealTime();
                                    deviceRealTime.setData(data);
                                    deviceRealTime.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                    // 返回给调用者的报文
                                    jsonString = JSON.toJSONString(deviceRealTime);
                                    log.info("大阳响应报文：" + jsonString);
                                    return jsonString;
                                }
                                /*查询到的设备接口返回的结果不是成功*/
                                if (!JsonConstant.RET_CODE_0000.equals(response.getCode())) {
                                    ResponseQueryDeviceRealTimeData data = new ResponseQueryDeviceRealTimeData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(curtime);
                                    data.setTradeRstCode(Integer.parseInt(response.getCode()));
                                    data.setTradeRstMessage(response.getMessage());

                                    ResponseQueryDeviceRealTime deviceRealTime = new ResponseQueryDeviceRealTime();
                                    deviceRealTime.setData(data);
                                    deviceRealTime.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                    // 返回给调用者的报文
                                    jsonString = JSON.toJSONString(deviceRealTime);
                                    log.info("大阳响应报文：" + jsonString);
                                    return jsonString;
                                }

                                /*查到设备之后现在去查询订单*/
                                ResponseQueryDeviceOrder orders = toBeijingService.queryDeviceOrder(deviceId, "", "", "", partnerCode, secret);
                                String remainingDays = retrievalRemainingDaysNew(orders);

                                /*设备上极有可能是没有正在使用的订单的*/
                                List<ResponseQueryDeviceRealTimeTradeDataPackageOrder> packageOrder = null;
                                if (null != response.getData().getPackage_order()) {
                                    /*组装返回数据*/
                                    packageOrder = new ArrayList<ResponseQueryDeviceRealTimeTradeDataPackageOrder>();
                                    ResponseQueryDeviceRealTimeTradeDataPackageOrder order = new ResponseQueryDeviceRealTimeTradeDataPackageOrder();
                                    order.setOrderCode(response.getData().getPackage_order().getOrderCode());
                                    order.setPackageName(response.getData().getPackage_order().getPackageName());
                                    order.setPackageCode(response.getData().getPackage_order().getPackageCode());
                                    order.setPackageType(response.getData().getPackage_order().getPackageType());
                                    order.setBuyType(response.getData().getPackage_order().getBuyType());
                                    order.setOrderPeriod(response.getData().getPackage_order().getOrderPeriod());
                                    order.setFlow(response.getData().getPackage_order().getFlow());
                                    order.setUsedFlow(response.getData().getPackage_order().getUsedFlow());
                                    order.setFlowUseRate(response.getData().getPackage_order().getFlowUseRate());
                                    order.setOrderUsedFlow(response.getData().getPackage_order().getOrderUsedFlow());
                                    order.setOrderDate(response.getData().getPackage_order().getOrderDate());
                                    order.setActiveDate(response.getData().getPackage_order().getActiveDate());
                                    order.setExpireDate(response.getData().getPackage_order().getExpireDate());
                                    order.setIsOrderRefuelingPackage(response.getData().getPackage_order().getIsOrderRefuelingPackage());
                                    order.setRefuelingPackage(null);
                                    packageOrder.add(order);

                                }
                                /*设备数据响应组装*/
                                List<ResponseQueryDeviceRealTimeTradeData> timeTradeData = new ArrayList<ResponseQueryDeviceRealTimeTradeData>();
                                ResponseQueryDeviceRealTimeTradeData tra = new ResponseQueryDeviceRealTimeTradeData();
                                tra.setDeviceId(response.getData().getDevice_id());
                                tra.setDeviceType("4");
                                tra.setOtaFlag(response.getData().getOta_flag());
                                tra.setBipFlag(response.getData().getBip_flag());
                                tra.setSoftSimIccid(response.getData().getMain_iccid());
                                tra.setSoftSimImsi(response.getData().getMultiImsi_flag());
                                tra.setLifecycle(response.getData().getLifecycle());
                                tra.setLifecycleStartTime(response.getData().getLifecycle_start_time());
                                tra.setLifecycleEndTime(response.getData().getLifecycle_end_time());
                                tra.setLifecycleSlientPeriod(response.getData().getLifecycle_slient_period());
                                tra.setLifecycleShutdownPeriod(response.getData().getLifecycle_shutdown_period());
                                tra.setPackageOrder(packageOrder);
                                tra.setRemainingDate(remainingDays);
                                timeTradeData.add(tra);

                                ResponseQueryDeviceRealTimeData data = new ResponseQueryDeviceRealTimeData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeType(tradeType);
                                data.setTradeTime(curtime);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeData(timeTradeData);

                                ResponseQueryDeviceRealTime deviceRealTime = new ResponseQueryDeviceRealTime();
                                deviceRealTime.setData(data);
                                deviceRealTime.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                // 返回给调用者的报文
                                jsonString = JSON.toJSONString(deviceRealTime);
                                log.info("大阳成功响应报文：" + jsonString);
                                return jsonString;

                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 3.0上面订单连接接口：计算归属领科的卡片理论上的剩余可用天数
     *
     * @param orders
     * @return
     */
    public String retrievalRemainingDaysNew(ResponseQueryDeviceOrder orders) {
        /*初始化一个剩余天数*/
        String remainingDays = "0";
        try {
            /*当前卡片未查到订单，默认卡片的理论剩余天数就是0*/
            if (null == orders || null == orders.getCode() || !JsonConstant.RET_CODE_0000.equals(orders.getCode()) || null == orders.getData() || null == orders.getData().getPackageOrder() || orders.getData().getPackageOrder().isEmpty()) {
                return remainingDays;
            }
            //1,获取到所有订单
            List<com.inter.entity.agatewaytobeijing.querydeviceorder.response.DevicePackageOrder> packageOrderList = orders.getData().getPackageOrder();
            //2,算下有几条未启用的订单：
            int countUnused = 0;
            for (int i = 0; i < packageOrderList.size(); i++) {
                com.inter.entity.agatewaytobeijing.querydeviceorder.response.DevicePackageOrder packageOrder = packageOrderList.get(i);
                //计算list中有几个未启用的订单
                if (packageOrder != null && packageOrder.getOrderStatus().equals(StringOutputConstant.CODE_ONE)) {
                    countUnused = countUnused + 1;
                }
            }
            //未启用的订单剩余天数
            int daysUnused = 0;
            //正在使用的订单还剩余的天数
            int daysUsing = 0;
            //通过循环订单来计算可用剩余天数
            for (com.inter.entity.agatewaytobeijing.querydeviceorder.response.DevicePackageOrder order : packageOrderList) {
                /*3，开始使用订单计算剩余天数*/
                if (order.getOrderStatus().equals(StringOutputConstant.CODE_TWO)) {
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyyMMdd");
                    /*预计结束时间*/
                    Date expireDate = simpleFormat.parse(order.getExpireDate());
                    /*今天的日期*/
                    Date now = simpleFormat.parse(simpleFormat.format(new Date()));
                    long expire = expireDate.getTime();
                    long to = now.getTime();
                    daysUsing = (int) ((expire - to) / (1000 * 60 * 60 * 24));
                }
                /*4，未启用订单计算剩余天数*/
                else if (order.getOrderStatus().equals(StringOutputConstant.CODE_ONE)) {
                    if (StringOutputConstant.CODE_ZERO.equals(order.getPackageType()) || StringOutputConstant.CODE_ONE.equals(order.getPackageType())) {
                        //符合未启用且套餐属于日程套餐或者日流量套餐的订单周期
                        String num = Integer.parseInt(order.getOrderPeriod()) + "";
                        daysUnused = Integer.parseInt(num) * countUnused;
                    } else if (StringOutputConstant.CODE_TWO.equals(order.getPackageType())) {
                        //符合未启用且套餐属于月流量套餐的订单周期
                        String num = Integer.parseInt(order.getOrderPeriod()) + "";
                        daysUnused = Integer.parseInt(num) * countUnused * 30;
                    } else if (StringOutputConstant.CODE_THREE.equals(order.getPackageType())) {
                        //符合未启用且套餐属于季度流量套餐的订单周期
                        String num = Integer.parseInt(order.getOrderPeriod()) + "";
                        daysUnused = Integer.parseInt(num) * countUnused * 30 * 3;
                    } else if (StringOutputConstant.CODE_FOUR.equals(order.getPackageType())) {
                        //符合未启用且套餐属于半年流量套餐的订单周期
                        String num = Integer.parseInt(order.getOrderPeriod()) + "";
                        daysUnused = Integer.parseInt(num) * countUnused * 30 * 6;
                    } else if (StringOutputConstant.CODE_FIVE.equals(order.getPackageType())) {
                        //符合未启用且套餐属于年流量套餐的订单周期
                        String num = Integer.parseInt(order.getOrderPeriod()) + "";
                        daysUnused = Integer.parseInt(num) * countUnused * 30 * 12;
                    }
                }
            }
            log.info("领科卡已使用的订单剩余天数：" + daysUsing + ";领科卡未启用的订单剩余天数：" + daysUnused);
            remainingDays = String.valueOf(daysUnused + daysUsing);
            return remainingDays;
        } catch (Exception e) {
            log.info("领科卡计算剩余天数过程异常：" + e);
        }
        return remainingDays;
    }
}
